﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Presenter.SearchRadicado;
using System.Collections.Generic;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Support;
using System.Linq;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using System.Text;

namespace MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls
{
    public partial class SearchRadicados : BaseControl, ISearchRadicadoView
    {

        #region fields

        SearchRadicadoPresenter _presenter;
        Dictionary<string, string> _formUrl;

        #endregion

        #region Properties

        public List<string> SelectedItems
        {
            get 
            { 
                string selectedIds = this.getSelectedRadicados(false);
                return selectedIds.Split(',').ToList();
            }
        }

        public string Source
        {
            get { return Page.Request.QueryString["source"]; }
        }

        public IEnumerable<Radicado> FoundedItems { get; set; }

        public string RadicadoId
        {
            get { return txtRadicado.Text.Trim(); }
        }

        public string Nit
        {
            get { return txtNit.Text.Trim(); }
        }

        public string Cedula
        {
            get { return txtCedula.Text.Trim(); }
        }

        public string FechaInicial 
        {
            get { return dtInicio.SelectedDate.ToString(); } 
        }

        public string FechaFinal 
        {
            get { return dtFin.SelectedDate.ToString(); }
        }

        public int PageIndex
        {
            get
            {
                return pgrTemplates.PageIndex;
            }
            set
            {
                pgrTemplates.PageIndex = value;
            }
        }

        public int PageSize
        {
            get
            {
                return pgrTemplates.PageSize;
            }
            set
            {
                pgrTemplates.PageSize = value;
            }
        }

        public int TotalRecords
        {
            get
            {
                return pgrTemplates.TotalRecords;
            }
            set
            {
                pgrTemplates.TotalRecords = value;
            }
        }

        public List<FileEntity> Files
        {
            get
            {
                if (Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "currentfile"] == null)
                    Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "currentfile"] = new List<FileEntity>();
                return Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "currentfile"] as List<FileEntity>;
            }
            set
            {
                Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "currentfile"] = value;
            }
        }

        public List<Roles> AllowedRibbonActions { get; set;}

        #endregion

        #region form event

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.Page.RegisterAjaxLoaderPlugin();
            btnSearch.AddLoader();
            _formUrl = new Dictionary<string, string>();
            _formUrl[GlobalConstants.METADATA_TERM_TIPO_RADICADO_ENTRADA] = "/sites/docs/_layouts/MS.InformationManagement.WP/InsertarRadicado.aspx?strategy=view&ListId={0}&ID={1}";
            _formUrl[GlobalConstants.METADATA_TERM_TIPO_RADICADO_SALIDA] = "/sites/docs/_layouts/MS.InformationManagement.WP/InsertarRadicadoSalida.aspx?strategy=view&ListId={0}&ID={1}";
            _formUrl[GlobalConstants.METADATA_TERM_TIPO_INTERNO] = "/sites/docs/_layouts/MS.InformationManagement.WP/RadicadoInterno.aspx?strategy=view&ListId={0}&ID={1}";
            txtCedula.RegularExpression(RegularExpresions.EXP_ALFANUMERIC_NO_TILDE, ExceptionConstants.ERROR_INVALID_CHARACTERS, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            
            txtNit.RegularExpression(RegularExpresions.EXP_ALFANUMERIC_NO_TILDE, ExceptionConstants.ERROR_INVALID_CHARACTERS, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            
            pgrTemplates.OnPageChanged += new Pager.PageChangeHandler(pgrTemplates_OnPageChanged);
            pgrTemplates.NumberOfPagesToDisplay = 10;
            PageIndex = 0;
            PageSize = 10;

            this.dtInicio.SelectedDate = DateTime.Now.AddDays(-30);
            this.dtFin.SelectedDate = DateTime.Now;
            if (Source == "interno")
                btnRespuesta.Visible = false;
            if (Source == "entrada")
                trFechas.Visible = true;
            //else
            //    btnRadicado.Visible = false;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new SearchRadicadoPresenter(this);
            if (IsPostBack) return;
            else
            _presenter.HandleLoad();
            //Cache.Remove(SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "files");
        }

        protected void action_nuevo(object sender, EventArgs e)
        { 
            try
            {
                string associatedIds = this.getSelectedRadicados(false);
                if (string.IsNullOrEmpty(associatedIds))
                    throw new Exception("Debe seleccionar un item para ejecutar esta acción");
                _presenter.SearchTRDValidation();
                string queryResult = "-1&associtedids=" + associatedIds + "&associatedaction=new";
                this.CloseWindowWithResponse(queryResult);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void action_response(object sender, EventArgs e)
        {
            try
            { 
                string associatedIds = this.getSelectedRadicados(false);
                if (string.IsNullOrEmpty(associatedIds))
                    throw new Exception("Debe seleccionar un item para ejecutar esta acción");
                _presenter.SearchValidation();
                string queryResult = "-1&associtedids=" + associatedIds + "&associatedaction=response";
                this.CloseWindowWithResponse(queryResult);

            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void action_search(object sender, EventArgs e)
        {
            PageIndex = 0;
            SearchMethod();
            pgrTemplates.BuildPager();
        }

        private void SearchMethod()
        {
            try
            {
                if (this.inputValidation())
                    _presenter.SearchItems();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void gvSenders_RowCreated(object sender, GridViewRowEventArgs e)
        {
            try
            {
                Radicado entity = e.Row.DataItem as Radicado;
                if (entity != null)
                {
                    if (e.Row.RowType != DataControlRowType.DataRow) return;

                    Label lblTipoRadicado = e.Row.FindControl("lblTipoRadicado") as Label;
                    lblTipoRadicado.Text = entity.Titulo;

                    if (Source == "entrada")
                    {
                        HyperLink link = e.Row.FindControl("lnkVer") as HyperLink;
                        HyperLink linkArchivo = e.Row.FindControl("lnkArchivo") as HyperLink;
                        link.NavigateUrl = string.Format("javascript:openDialogAutoSizeWithOutRefresh('" + _formUrl[entity.Titulo] + "')", entity.ListId.ToString(), entity.Id.Value);

                        if (entity.AttachedFiles.Count > 0)
                        {
                            var file = entity.AttachedFiles.Where(x => x.IsMainDocument == true).FirstOrDefault();
                            if (file != null)
                            {
                                linkArchivo.NavigateUrl = string.Format("/sites/docs/_layouts/MS.InformationManagement.Controls/FileViewer.aspx?FileName={0}&Type=2", file.FileName);
                                Files.Add(new FileEntity() { IsMainDocument = file.IsMainDocument, CreationDate = file.CreationDate, FileName = file.FileName, FileSize = file.FileSize, FileContent = file.FileContent });
                            }
                            else
                                linkArchivo.Visible = false;
                        }
                        else
                            linkArchivo.Visible = false;
                    }
                    else
                    {
                        e.Row.Cells[8].Visible = false;
                        gvRadicados.HeaderRow.Cells[8].Visible = false;

                        e.Row.Cells[9].Visible = false;
                        gvRadicados.HeaderRow.Cells[9].Visible = false;
                    }

                    e.Row.Cells[7].Visible = false;
                    gvRadicados.HeaderRow.Cells[7].Visible = false;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void action_close(object sender, EventArgs e)
        {
            this.CloseWindow();
        }

        protected void action_add(object sender, EventArgs e)
        {
            try
            {
                string associatedIds = this.getSelectedRadicados(true);
                if (string.IsNullOrEmpty(associatedIds))
                    throw new Exception("Debe seleccionar un item para ejecutar esta acción");

                Cache["remitenteID"] = associatedIds;
                this.CloseWindowWithResponse(associatedIds);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void gvSenders_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvRadicados.PageIndex = e.NewPageIndex;
                _presenter.SearchItems();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        void pgrTemplates_OnPageChanged(object sender, Controls.PageChangeEventArgs e)
        {
            SearchMethod();
            pgrTemplates.BuildPager();
        }

        #endregion

        #region Implemented Methods

        public void LoadFoundedItems()
        {
            try
            {
                gvRadicados.DataSource = FoundedItems.ToList();
                gvRadicados.DataBind();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }
        public void Show()
        {
            var allowedaction = (from act in AllowedRibbonActions
                                 where act.Role.ToUpper() == GlobalConstants.ROLE_CONTACTS.ToUpper()
                                         select act).FirstOrDefault();
            if (allowedaction != null)
                btnContacto.Visible = true;
            else
                btnContacto.Visible = false;
        }

        #endregion

        #region Private Methods

        private bool inputValidation()
        {
            if (string.IsNullOrEmpty(txtCedula.Text) &&
                string.IsNullOrEmpty(txtNit.Text) &&
                string.IsNullOrEmpty(txtRadicado.Text))
            {
                if (this.Source == "entrada")
                    HandleWarning("Debe seleccionar por lo menos un criterio de busqueda diferente a las fechas");
                else
                    HandleWarning("Debe seleccionar por lo menos un criterio de busqueda");

                return false;
            }
            return true;
        }

        private string getSelectedRadicados(bool isNew)
        { 
            try
            {
                string selectedItems = string.Empty;
                foreach(GridViewRow row in gvRadicados.Rows)
                {
                    var chkControl = row.Cells[0].FindControl("rbSeleccion") as RadioButton;
                    if (chkControl.Checked)
                    {
                        if (!isNew)
                            selectedItems += string.IsNullOrEmpty(selectedItems) ? row.Cells[1].Text : "," + row.Cells[1].Text;
                        else
                            selectedItems = (row.FindControl("hdfIdPersona") as HiddenField).Value;
                    }
                }
                return selectedItems;
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
            return null;
        }

        #endregion

        protected void btnContacto_Click(object sender, EventArgs e)
        {
           this.DesplegarVentanaModal(SPContext.Current.Web.Url + "/_layouts/MS.InformationManagement.WP/ContactsManager.aspx?Dlg=1", "Sistema de Gestión Documental", 500, 460, this.Page);
        }
        
    }
}
